/*
 * Copyright 2010 Christian Schindelhauer, Peter Thiemann, Faisal Aslam, Luminous Fennell and Gidon Ernst.
 * All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 * This code is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License version 3 for more details (a copy is
 * included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU General Public License
 * version 3 along with this work; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA
 *
 * Please contact Faisal Aslam
 * (aslam AT informatik.uni-freibug.de or studentresearcher AT gmail.com)
 * if you need additional information or have any questions.
 */
package takatuka.vm.autoGenerated.forExceptionPrettyPrint;

import java.io.*;
import takatuka.classreader.dataObjs.*;
import takatuka.classreader.dataObjs.attribute.*;
import takatuka.classreader.logic.util.*;

import takatuka.optimizer.cpGlobalization.logic.util.*;
import takatuka.tukFormat.dataObjs.*;
import takatuka.tukFormat.logic.file.*;
import java.util.*;

/**
 * <p>Title: </p>
 * <p>Description:
 *
 * It generates method names property file.
 *
 * </p>
 * @author Faisal Aslam
 * @version 1.0
 */
class MethodNamesPropertyFile {

    private static final MethodNamesPropertyFile myObj = new MethodNamesPropertyFile();
    private static StringBuffer methodNamePropBuffer = new StringBuffer();
    private static final String METHODNAME_PROPERTY_FILE_NAME = "methodNames.properties";
    private static final String SOURCENAME_PROPERTY_FILE_NAME = "sourceToMethodID.properties";
    private static final String SOURCE_FULL_QUALIFIED_PATH = "sourceFullQualifiedPath.properties";
    private static StringBuffer sourceFullQualifiedPath = new StringBuffer();
    private static String prevFileName = new String();
    private static final HashMap<String, String> sourceToMethodIDMap = new HashMap();
    private TreeMap<Integer, String> methodIDToMethodNamePropLine = new TreeMap<Integer, String>();
    TreeMap<String, Integer> methodNameToID = new TreeMap<String, Integer>();

    /**
     * the constructor is private
     */
    private MethodNamesPropertyFile() {
    }

    public static MethodNamesPropertyFile getInstanceOf() {
        return myObj;
    }

    /**
     * Go to all the class files and generate corresponding methods names.
     * The syntax of method names is as followed.
     * fullyQualifiedClassName.methodName(sourceFile.java)
     *
     * @param method
     * @param cFile
     */
    public void execute(LFMethodInfo method, ClassFile cFile) {
        Oracle oracle = Oracle.getInstanceOf();
        String fullyQualifiedClassName = cFile.getFullyQualifiedClassName();
        String methodName = oracle.methodOrFieldName(method);
        String sourceFileName = getSourceFileName(cFile);
        int methodID = method.getReferenceIndex();
        String methodPropertyFileLine = methodID + "="
                + fullyQualifiedClassName.replace("/", ".") + "."
                + methodName + "(" + sourceFileName + ")\n";
        methodIDToMethodNamePropLine.put(methodID, methodPropertyFileLine);
        String methodStr = oracle.getMethodOrFieldString(method);
        methodNameToID.put(methodStr, methodID);
        String value = sourceToMethodIDMap.get(sourceFileName);
        if (value == null) {
            value = "";
        }
        if (value.length() != 0) {
            value += ",";
        }
        value += methodID;

        sourceToMethodIDMap.put(sourceFileName, value);
        //methodNamePropBuffer.append(methodPropertyFileLine);

        if (!prevFileName.equals(sourceFileName)) {
            sourceFullQualifiedPath.append(sourceFileName + "=" + fullSourcePath(cFile, sourceFileName) + "\n");
            prevFileName = sourceFileName;
        }

    }

    private String fullSourcePath(ClassFile cFile, String sourceFileName) {
        String pathSplit[] = cFile.getSourceFileNameWithPath().split("/");
        StringBuilder returnData = new StringBuilder();

        for (int i = 0; i < pathSplit.length - 1; i++) {
            returnData.append(pathSplit[i]).append("/");
        }

        returnData.append(sourceFileName);

        return returnData.toString();
    }

    public static String getSourceFileName(ClassFile cFile) {
        AttributeInfoController attContr = cFile.getAttributeInfoController();
        Oracle oracle = Oracle.getInstanceOf();
        MultiplePoolsFacade gcp = cFile.getConstantPool();
        for (int loop = 0; loop < attContr.getCurrentSize(); loop++) {
            AttributeInfo attInfo = (AttributeInfo) attContr.get(loop);
            String attName = oracle.getUTF8(attInfo.getAttributeNameIndex().intValueUnsigned(), gcp);
            if (attName.equals("SourceFile")) {
                return oracle.getUTF8(((SourceFileAtt) attInfo).getSourcefileIndex().intValueUnsigned(), gcp);
            }
        }
        return "";
    }

    /**
     *
     * @param propertyFileName
     * @param buffer
     */
    public static void writeInPropertyFile(String propertyFileName, StringBuffer buffer) {
        try {
            String fileNamePath = LFWriter.getOutputDirectory() + "/" + propertyFileName;
            File file = new File(fileNamePath);
            if (file.exists()) {
                file.delete();
            }
            RandomAccessFile rm = new RandomAccessFile(file, "rw");
            rm.writeBytes(buffer.toString());
            rm.close();
        } catch (Exception d) {
            d.printStackTrace();
            Miscellaneous.exit();
        }

    }

    /**
     * 
     */
    public void writeInPropertyFile() {
        Iterator<Integer> methodIdIterator = methodIDToMethodNamePropLine.keySet().iterator();
        while (methodIdIterator.hasNext()) {
            int methodID = methodIdIterator.next();
            methodNamePropBuffer.append(methodIDToMethodNamePropLine.get(methodID));
        }
        writeInPropertyFile(METHODNAME_PROPERTY_FILE_NAME, methodNamePropBuffer);
        writeInPropertyFile(SOURCENAME_PROPERTY_FILE_NAME, writeMapInPropertyFile());
        writeInPropertyFile(SOURCE_FULL_QUALIFIED_PATH, sourceFullQualifiedPath);

    }

    private StringBuffer writeMapInPropertyFile() {
        StringBuffer ret = new StringBuffer();
        Set<String> sourceNameSet = sourceToMethodIDMap.keySet();
        Iterator<String> sourceNameIt = sourceNameSet.iterator();
        while (sourceNameIt.hasNext()) {
            String sourceName = sourceNameIt.next();
            String methodIDs = sourceToMethodIDMap.get(sourceName);
            ret.append(sourceName + "=" + methodIDs + "\n");
        }
        return ret;

    }
}
